import os
import uuid
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin, DestroyModelMixin, UpdateModelMixin, ListModelMixin, \
    RetrieveModelMixin
from rest_framework.permissions import IsAuthenticated

from common.utils import build_tree_category, get_image_url
from goods.models import Category, Attr, Goods
from goods.serializers import GoodsCategorySerializer, GoodsAttrSerializer, GoodsSerializer, GoodsFilter


class GoodsCategoryView(GenericViewSet, CreateModelMixin, DestroyModelMixin, UpdateModelMixin, ListModelMixin,
                        RetrieveModelMixin):
    queryset = Category.objects.all().order_by('id')
    serializer_class = GoodsCategorySerializer
    permission_classes = [IsAuthenticated]

    def list(self, request, *args, **kwargs):
        level = request.query_params.get('level')
        if level:
            queryset = self.queryset.filter(level__lte=int(level))
        else:
            queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        tree_category = build_tree_category(serializer.data)
        return Response(tree_category)


class GoodsAttrView(GenericViewSet, CreateModelMixin, DestroyModelMixin, UpdateModelMixin, ListModelMixin,
                    RetrieveModelMixin):
    queryset = Attr.objects.all().order_by('-id')
    serializer_class = GoodsAttrSerializer
    permission_classes = [IsAuthenticated]
    filterset_fields = ['_type']


class GoodsView(GenericViewSet, ListModelMixin, DestroyModelMixin, CreateModelMixin):
    queryset = Goods.objects.all().order_by('id')
    serializer_class = GoodsSerializer
    permission_classes = [IsAuthenticated]
    filterset_class = GoodsFilter


class GoodsImageView(APIView):
    def post(self, request):
        """
        上传图片
        """
        file = request.FILES.get('file')
        if not file:
            return Response({'code': 400, 'msg': '没有上传文件'})
        if file.size > settings.MAX_FILE_SIZE:
            return Response({'code': 400, 'msg': '文件不能超过2M'})
        if file.name.split('.')[-1] not in settings.ALLOWED_EXTENSIONS:
            return Response({'code': 400, 'msg': '文件格式不正确'})

        # 生成唯一文件名
        file_extension = os.path.splitext(file.name)[1]
        unique_filename = str(uuid.uuid4()) + file_extension

        # 文件路径
        file_path = os.path.join(settings.MEDIA_ROOT, unique_filename)
        # 存入文件
        with open(file_path, 'wb') as f:
            for chunk in file.chunks():
                f.write(chunk)
        image_url = get_image_url(request, unique_filename)
        return Response({'code': 200, 'msg': '照片上传ok', 'data': image_url})


class GoodsImageFileView(APIView):
    def get(self, request, name):
        """
        获取图片图片
        """
        # 1. 获取路径
        path = os.path.join(settings.MEDIA_ROOT, name)
        image_url = request.build_absolute_uri('/') + 'api/goods' + settings.MEDIA_URL + name
        # 2. 判断文件存不存在
        if os.path.isfile(path):
            # 3. 存在的话使用Django内置的文件响应去打开文件
            return Response({'image_url': image_url})
        # 4. 不存在的话给出提示
        return Response({'code': '400', 'msg': '没有找到该文件！'})
